package com.zhongxi.guoyuan.fragment;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.ImageBannerAdapter;
import com.zhongxi.guoyuan.adapter.beautifulStore.BeautifulProjectAdapter;
import com.zhongxi.guoyuan.adapter.beautifulStore.NewBeautifulAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.service.ServiceItemData;
import com.zhongxi.guoyuan.entity.service.ServiceResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DeviceUtils;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.sliding.CustomViewPager;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zhongxi.guoyuan.R.id.rl_content;

public class MainStoreFragment extends BaseFragment implements View.OnClickListener, MyScrollView.OnScrollListener {

    private static final long TIMESTOP = 200;
    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.iv_service)
    ImageView ivService;
    @Bind(R.id.iv_dot)
    ImageView ivDot;
    @Bind(rl_content)
    RelativeLayout rlContent;
    @Bind(R.id.title)
    RelativeLayout title;
    @Bind(R.id.viewflow)
    ViewFlow viewflow;
    @Bind(R.id.viewflowdic)
    CircleIndicator viewflowdic;
    @Bind(R.id.flow)
    FrameLayout flow;
    @Bind(R.id.ll_free)
    LinearLayout llFree;
    @Bind(R.id.ll_nocard)
    LinearLayout llNocard;
    @Bind(R.id.ll_nomarket)
    LinearLayout llNomarket;
    @Bind(R.id.ll_goodcharacter)
    LinearLayout llGoodcharacter;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.et_clear)
    TextView etClear;
    @Bind(R.id.et_hint_text)
    TextView etHintText;
    @Bind(R.id.et_text_cancel)
    TextView etTextCancel;
    @Bind(R.id.iv_search)
    ImageView ivSearch;
    @Bind(R.id.tabLayout)
    TabLayout tabLayout;
    @Bind(R.id.viewPager)
    CustomViewPager viewPager;
    @Bind(R.id.myScrollView)
    MyScrollView myScrollView;
    @Bind(R.id.subscribe_text_recently)
    TextView subscribeTextRecently;
    @Bind(R.id.subscribe_text_topScore)
    TextView subscribeTextTopScore;
    @Bind(R.id.subscribe_text_great)
    TextView subscribeTextGreat;
    @Bind(R.id.lvList)
    NoScrollListView lvList;
    @Bind(R.id.linearLayout)
    LinearLayout linearLayout;
    @Bind(R.id.scrollBody)
    LinearLayout scrollBody;
    @Bind(R.id.linearBegin)
    LinearLayout linearBegin;
    @Bind(R.id.linearStop)
    LinearLayout linearStop;


    private ProgressDialog mDialog;
    private PopupWindow pw;
    private int count;
    public static final int requestFulsh = 500;
    public static final int requestFulshConver = 600;
    private ImageBannerAdapter mBannerAdapter;
    private String trim = "";
    private BeautifulProjectAdapter projectAdapter;
    private String type;
    private int orderby = 1;
    private NewBeautifulAdapter adapter;
    private View loadMoreView;
    private TextView text_loadmore;
    private ProgressBar progressBar;
    private Map<String, String> map;
    private boolean isMeasured;
    private int measuredHeight;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_store, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("美豆美容");
        ViewTreeObserver treeObserver = linearLayout.getViewTreeObserver();
        treeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    measuredHeight = linearLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });
        //设置轮播图片高度
        ImageUtils.setHeight(getActivity(), Constants.flowRate, flow);
        adapter = new NewBeautifulAdapter(context, list);
        lvList.setAdapter(adapter);
        addFooterView();
    }

    private void addFooterView() {
        loadMoreView = LayoutInflater.from(getContext()).inflate(R.layout.load_moredata, null);
        text_loadmore = (TextView) loadMoreView.findViewById(R.id.text_loadmore);
        progressBar = (ProgressBar) loadMoreView.findViewById(R.id.progressbar);
        progressBar.setVisibility(View.GONE);
        loadMoreView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadMore();
            }
        });
        lvList.addFooterView(loadMoreView);
    }

    private void loadMore() {
        pageNum++;
        if (!TextUtils.isEmpty(trim)) {
            getPost();
        } else {
            getData();
        }
    }

    private void lunbo(List<AdData> data) {
        //初始化轮播控件
        viewflow.setFlowIndicator(viewflowdic);
        if (data.size() > 0) {
            viewflow.setSideBuffer(data.size()); // 实际图片数量
        } else {
            viewflow.setSideBuffer(1); // 实际图片数量
        }
        if (mBannerAdapter == null) {
            mBannerAdapter = new ImageBannerAdapter(getActivity(), data);
        } else {
            mBannerAdapter.replaceAll(data);
        }
        viewflow.setAdapter(mBannerAdapter);
        viewflow.startAutoFlowTimer();
    }

    @Override
    protected void initData() {
        super.initData();
        projectAdapter = new BeautifulProjectAdapter(getChildFragmentManager());
//        projectAdapter.setPrimary(trim);
        viewPager.setAdapter(projectAdapter);
        tabLayout.setupWithViewPager(viewPager);

//        adapter = new ProjectAdapter(context, list);
//        lvList.setAdapter(adapter);
        getAds();
        //获取广告轮播
    }

    private void getData() {
        type = "data";
        String getStr = "&page=" + pageNum + "&orderby=" + orderby;
        getServer(Url.SERVICE_LIST, null, getStr, false, null, "get");
    }

    private void getPost() {
        type = "data";
        map = new HashMap<>();
        map.clear();
        map.put("content", trim);
//        map.put("orderby", orderby + "");
        String getStr = "&page=" + pageNum;
        getServer(Url.INNER_SERVICE, map, getStr, false, null, "post");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        ivSearch.setOnClickListener(this);
        rlContent.setOnClickListener(this);
        myScrollView.setOnScrollListener(this);
        etTextCancel.setOnClickListener(this);
        etClear.setOnClickListener(this);
        etSearch.setOnClickListener(this);

        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(context, ProjectDetailActivity.class);
                intent.putExtra("id", list.get(i).getId());
                getActivity().startActivityForResult(intent, 100);
            }
        });
        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if (b) {
                    etTextCancel.setVisibility(View.VISIBLE);
                    etTextCancel.setText("取消");
                    etClear.setVisibility(View.GONE);
                    etHintText.setVisibility(View.GONE);
                }
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    etClear.setVisibility(View.VISIBLE);
                    etTextCancel.setText("搜索");
                } else {
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setText("取消");
//                    etTextCancel.setText("搜索");
                }
                etHintText.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                getActivity().finish();
                break;
            case R.id.iv_search:
                pageNum = 1;
                if (TextUtils.isEmpty(etSearch.getText().toString().trim())) {
                    trim = "";
                } else {
                    trim = etSearch.getText().toString().trim();
                }

                if (!TextUtils.isEmpty(trim)) {
                    getPost();
                } else {
                    getData();
                }
//                EventBus.getDefault().post(new EventMessage(trim));
//                projectAdapter.setPrimary(trim);
//                projectAdapter.notifyDataSetChanged();

                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_text_cancel:

                if (TextUtils.isEmpty(etSearch.getText().toString().trim())) {
                    trim = "";
                } else {
                    trim = etSearch.getText().toString().trim();
                }
                if (trim.length() > 0) {
                    pageNum = 1;

                    if (!TextUtils.isEmpty(trim)) {
                        getPost();
                    } else {
                        getData();
                    }
                } else {
                    etSearch.setText("");
                    etHintText.setVisibility(View.VISIBLE);
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setVisibility(View.GONE);
                    getData();
                }
                CommonTool.hideSoft(etSearch, context);

                break;
            case R.id.et_clear:

                etSearch.setText("");
                etHintText.setVisibility(View.VISIBLE);
                etTextCancel.setText("取消");
//                etTextCancel.setText("搜索");
                etTextCancel.setVisibility(View.VISIBLE);
//                getData();
                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_search:
                etTextCancel.setVisibility(View.VISIBLE);
                break;
            case rl_content:
                if (CommonTool.checkApkExist(getContext(),"com.tencent.mobileqq")){
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "mqqwpa://im/chat?chat_type=wpa&uin="+Constants.QQ_NUM+"&version=1")));
                }else {
                    showShortToast("未安装QQ");
                }
                break;
        }
    }




    @Override
    public void onResume() {
        super.onResume();
    }





    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private List<ServiceItemData> list = new ArrayList<>();

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if (type.equals("ad")) {
                AdResult adResult = gson.fromJson(response, AdResult.class);
                MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                lunbo(adResult.getData());
                getData();
            } else if (type.equals("data")) {
                ServiceResult serviceResult = gson.fromJson(response, ServiceResult.class);
                if (serviceResult.getSafeobj() != null && !"".equals(serviceResult.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(serviceResult.getSafeobj());
                }

                if (pageNum > 1) {
                    if (null == serviceResult.getData() || serviceResult.getData().size() == 0) {
                        showShortToast("没有更多了");
                        text_loadmore.setText("查看更多");
                        pageNum--;
                        progressBar.setVisibility(View.GONE);
                        return;
                    }
                }
                if (pageNum == 1) {
                    list.clear();
                }
                if (!TextUtils.isEmpty(trim)) {
                    if (null != serviceResult.getData() && serviceResult.getData().size() > 0) {

                        list.addAll(serviceResult.getData());
                    } else {
                        text_loadmore.setVisibility(View.GONE);
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(context, "抱歉,搜索不到与”" + trim + "“相关的关键词", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (null != serviceResult.getData() && serviceResult.getData().size() > 0) {
                        list.addAll(serviceResult.getData());
                        text_loadmore.setVisibility(View.VISIBLE);
                        text_loadmore.setText("查看更多");

                    }
                }
                progressBar.setVisibility(View.GONE);
                adapter.notifyDataSetChanged();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取广告展示
     */
    private void getAds() {
        type = "ad";
        String getStr = "&type=2";
        getServer(Url.SHOW_ADS, null, getStr, false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestFulsh) {
            pw.dismiss();
        } else if (requestCode == requestFulshConver) {
            pw.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= measuredHeight) {
            if (scrollBody.getParent() != linearStop) {
                linearBegin.removeView(scrollBody);
                linearBegin.setLayoutParams(new LinearLayout.LayoutParams(scrollBody.getMeasuredWidth(), scrollBody.getMeasuredHeight()));
                linearStop.addView(scrollBody);
            }
        } else {
            if (scrollBody.getParent() != linearBegin) {
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
    }

    @OnClick({R.id.subscribe_text_recently, R.id.subscribe_text_topScore, R.id.subscribe_text_great, R.id.ll_goodcharacter})
    public void onViewClicked(View view) {

        if (TextUtils.isEmpty(etSearch.getText().toString().trim())) {
            trim = "";
        } else {
            trim = etSearch.getText().toString().trim();
        }

        switch (view.getId()) {
            case R.id.subscribe_text_recently:
                if (scrollBody.getParent() != linearBegin) {
                    myScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                }
                subscribeTextRecently.setTextColor(getResources().getColor(R.color.title_red));
                subscribeTextTopScore.setTextColor(getResources().getColor(R.color.gohere));
                subscribeTextGreat.setTextColor(getResources().getColor(R.color.gohere));
                pageNum = 1;
                orderby = 1;
                if (!TextUtils.isEmpty(trim)) {
                    getPost();
                } else {
                    getData();
                }
                break;
            case R.id.subscribe_text_topScore:
                if (scrollBody.getParent() != linearBegin) {
                    myScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                }
                subscribeTextRecently.setTextColor(getResources().getColor(R.color.gohere));
                subscribeTextTopScore.setTextColor(getResources().getColor(R.color.title_red));
                subscribeTextGreat.setTextColor(getResources().getColor(R.color.gohere));
                pageNum = 1;
                orderby = 2;
                if (!TextUtils.isEmpty(trim)) {
                    getPost();
                } else {
                    getData();
                }
                break;
            case R.id.subscribe_text_great:
                if (scrollBody.getParent() != linearBegin) {
                    myScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                }
                subscribeTextRecently.setTextColor(getResources().getColor(R.color.gohere));
                subscribeTextTopScore.setTextColor(getResources().getColor(R.color.gohere));
                subscribeTextGreat.setTextColor(getResources().getColor(R.color.title_red));
                pageNum = 1;
                orderby = 3;
                if (!TextUtils.isEmpty(trim)) {
                    getPost();
                } else {
                    getData();
                }
                break;
            case R.id.ll_goodcharacter:
                Intent intent = new Intent(context, HtmlActivity.class);
                intent.putExtra("type", "doudouRule");
                startActivity(intent);
                break;
        }
    }
}